﻿#include "ZRoundWidget.h"

#include <QBitmap>
#include <QPainter>
#include <QResizeEvent>
#include <QDebug>

ZRoundWidget::ZRoundWidget(QWidget *parent)
    : QWidget(parent)
{
}

ZRoundWidget::~ZRoundWidget()
{

}

/**
 * @brief 设置圆角.
 * @param rect
 *   当QFrame在布局中时，无法直接获取自身的大小.
 * @param xRadius
 * @param yRadius
 */
void ZRoundWidget::setRound(qreal xRadius, qreal yRadius)
{
    m_xRadius = xRadius;
    m_yRadius = yRadius;
    update();
}

void ZRoundWidget::setBorder(int width, const QColor &color, Qt::PenStyle pen_style)
{
    m_border_pen.setWidth(width);
    m_border_pen.setColor(color);
    m_border_pen.setStyle(pen_style);
}

/**
 * @brief
 *   当QWidget在布局中时,rect(),size等都是不准确的.
 *   需要实时计算.
 * @param event
 */
void ZRoundWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    m_size = event->size();
}

void ZRoundWidget::paintEvent(QPaintEvent *event)
{
    // 根据当前大小，得到当前矩形.
    QRect rc = rect();
    rc.setWidth(m_size.width());
    rc.setHeight(m_size.height());

    // 自绘Bitmap，并设置为mask（掩膜）
    // mask就是像素开关数组，1表示打开(可见)，0为关闭（不可见）
    QBitmap round_mask(rc.width(), rc.height());
    round_mask.fill(Qt::color0);

    QPainterPath round_path;
    // 测试发现addRoundRect没有addRoundedRect效果好.
    round_path.addRoundedRect(rc, m_xRadius, m_yRadius);
    QPainter painter(&round_mask);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.drawPath(round_path);
    painter.fillPath(round_path, QBrush(Qt::color1));
    setMask(round_mask);

    // 绘制边框
    QPainter painter1(this);
    painter1.setRenderHint(QPainter::Antialiasing, true);
    QPainterPath border_path;

    int pen_width = m_border_pen.width();
    border_path.addRoundedRect(rc.adjusted(pen_width, pen_width, -pen_width, -pen_width),
                               m_xRadius, m_yRadius);
    painter1.setPen(m_border_pen);
    painter1.drawPath(border_path);
    painter1.fillPath(border_path, Qt::white);
}

